#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<errno.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#define DEFAULTPORT         2014
#define DEFAULT_BACKLOG     20
int main(int argc ,char *argv[])
{
    struct sockaddr_in socket_addr;
    struct sockaddr_in socket_acpt;
    char buf[30] = {0};
    int recv_len;
    int acpt_len = sizeof(struct sockaddr_in);
    int accept_clt;

    memset(&socket_addr, 0, sizeof(socket_addr));
    socket_addr.sin_family = AF_INET;
    socket_addr.sin_port = htons(DEFAULTPORT);
    socket_addr.sin_addr.s_addr = htons(INADDR_ANY);
    bzero(&(socket_addr.sin_zero), 8);


    int socket_fd = socket(PF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1){
        printf("Socket Error log is : %s\n", strerror(errno));
        close(socket_fd);
        exit(0);
    }


    if (bind(socket_fd, (struct sockaddr *)&socket_addr, sizeof(struct sockaddr_in)) == -1){
        printf("Bind Error log is : %s\n", strerror(errno));
        close(socket_fd);
        exit(0);
    }
    else
    {
        if (listen(socket_fd, DEFAULT_BACKLOG) == -1){
            printf("Listen Error log is : %s\n", strerror(errno));
            close(socket_fd);
            exit(0);
        }
        else
        {
            while(1){
                accept_clt = accept(socket_fd, (struct sockaddr *)&socket_acpt, (socklen_t *)&acpt_len);
                if(accept_clt == -1){
                    printf("Accept Error log is : %s\n", strerror(errno));
                    close(socket_fd);
                    exit(0);
                }
                printf("received a connection from %s\n", inet_ntoa(socket_acpt.sin_addr));
                recv_len = recv(accept_clt, buf, sizeof(buf), MSG_WAITALL);
                if (recv_len == -1){
                    printf("Accept Error log is : %s\n", strerror(errno));
                    close(socket_fd);
                    exit(0);
                }
                printf("recv data : %s\n", buf);
                memset(buf, 0, sizeof(buf));
            }
        }
    }
    return 0;
}
